package com.demo.systemmonitor;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.demo.systemmonitor.LineChart;
import com.demo.systemmonitor.data.CpuData;
import com.demo.systemmonitor.data.CpuInfo;
import com.demo.systemmonitor.utils.CpuUtils;
import com.demo.systemmonitor.utils.MemoryUtils;
import com.demo.systemmonitor.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Arrays;
import android.os.SystemClock;

public class FloatingMonitorWindow {
    private static final String TAG = "FloatingMonitorWindow";
    private static WindowManager windowManager;
    private static View floatingView;
    private static boolean isWindowVisible = false;
    private static boolean isExpanded = false;
    
    // 静态悬浮窗实例
    private static FloatingMonitorWindow currentInstance = null;
    
    // 小窗口视图引用
    private TextView tvCpuUsage, tvCpuTemp, tvCpuFreq;
    private TextView tvMemoryUsage, tvMemoryTotal, tvMemoryUsed;
    
    // 大窗口视图引用
    private LineChart cpuUsageChart;
    private LineChart memoryUsageChart;
    private TextView tvCpuModel, tvBaseSpeed;
    private TextView tvUsage, tvSpeed, tvCpuTempLarge, tvCpuTempPeak;
    private TextView tvUsagePeak; // 新增：最高使用率
    private TextView tvTotalMemory, tvUsedMemory, tvAvailableMemory, tvMemoryUsagePercent;
    private TextView tvUptime;
    
    // 数据存储
    private List<Float> cpuUsageData = new ArrayList<>();
    private List<Float> cpuTempData = new ArrayList<>();
    private List<Float> cpuFreqData = new ArrayList<>();
    private List<Float> memoryUsageData = new ArrayList<>();
    
    // 定时器
    private Timer timer;
    private Handler handler;
    
    // 检测并移除现有窗口
    private void removeExistingWindow() {
        if (windowManager != null && floatingView != null) {
            try {
                windowManager.removeView(floatingView);
                Log.d(TAG, "Removed existing floating window");
            } catch (Exception e) {
                Log.e(TAG, "Error removing existing window", e);
            }
        }
        // 重置状态
        isWindowVisible = false;
        isExpanded = false;
        stopDataUpdate();
    }
    
    // 初始化小窗口视图
    private void initSmallViews() {
        tvCpuUsage = floatingView.findViewById(R.id.tv_floating_cpu_usage);
        tvCpuTemp = floatingView.findViewById(R.id.tv_floating_cpu_temp);
        tvCpuFreq = floatingView.findViewById(R.id.tv_floating_cpu_freq);
        tvMemoryUsage = floatingView.findViewById(R.id.tv_floating_memory_usage);
        tvMemoryTotal = floatingView.findViewById(R.id.tv_floating_memory_total);
        tvMemoryUsed = floatingView.findViewById(R.id.tv_floating_memory_used);
        
        // 移除展开按钮相关代码
    }
    
    // 初始化大窗口视图
    private void initLargeViews() {
        cpuUsageChart = floatingView.findViewById(R.id.chart_cpu_usage);
        memoryUsageChart = floatingView.findViewById(R.id.chart_memory_usage);
        tvCpuModel = floatingView.findViewById(R.id.tv_cpu_model);
        tvBaseSpeed = floatingView.findViewById(R.id.tv_base_speed);
        tvUsage = floatingView.findViewById(R.id.tv_usage);
        tvSpeed = floatingView.findViewById(R.id.tv_speed);
        tvCpuTempLarge = floatingView.findViewById(R.id.tv_cpu_temp);
        tvCpuTempPeak = floatingView.findViewById(R.id.tv_cpu_temp_peak);
        tvUsagePeak = floatingView.findViewById(R.id.tv_usage_peak);
        tvTotalMemory = floatingView.findViewById(R.id.tv_total_memory);
        tvUsedMemory = floatingView.findViewById(R.id.tv_used_memory);
        tvAvailableMemory = floatingView.findViewById(R.id.tv_available_memory);
        tvMemoryUsagePercent = floatingView.findViewById(R.id.tv_memory_usage_percent);
        tvUptime = floatingView.findViewById(R.id.tv_uptime);
        
        // 移除缩小按钮相关代码
        
        // 初始化最高值显示
        tvUsagePeak.setText("--%");
        tvCpuTempPeak.setText("--°C");
        
        // 初始化峰值变量
    }
    
    // 移除展开和缩小方法，不再需要
    
    // 恢复原始的 setupCharts 方法
    private void setupCharts() {
        cpuUsageChart.setLeftAxis("%", 100f);
        cpuUsageChart.setRightAxisEnabled(true, "°C", 100f);
        
        memoryUsageChart.setLeftAxis("%", 100f);
        memoryUsageChart.setRightAxisEnabled(true, "MHz", 2000f);
    }
    
    // 初始化CPU信息
    private void initCpuInfo() {
        CpuInfo cpuInfo = CpuUtils.getCpuInfo();
        if (cpuInfo != null) {
            tvCpuModel.setText(cpuInfo.getModel());
            tvBaseSpeed.setText(cpuInfo.getBaseSpeed());
        }
    }
    
    // 恢复原始的 updateCpuData 方法
    private void updateCpuData() {
        CpuData cpuData = CpuUtils.getCpuData();
        if (cpuData != null) {
            float usage = cpuData.getUsage();
            float frequency = cpuData.getFrequency();
            Float tempC = cpuData.getTemperatureC();
            Float peakTemp = cpuData.getPeakTemperature();
            Float peakUsage = cpuData.getPeakUsage();
            
            // 更新UI
            tvUsage.setText(String.format("%.1f%%", usage));
            tvSpeed.setText(String.format("%.1f GHz", frequency / 1000f));
            tvCpuTempLarge.setText(tempC == null ? "--°C" : String.format("%.1f°C", tempC));
            
            // 直接使用库中的峰值数据
            tvUsagePeak.setText(peakUsage == null ? "--%" : String.format("%.1f%%", peakUsage));
            tvCpuTempPeak.setText(peakTemp == null ? "--°C" : String.format("%.1f°C", peakTemp));
            
            // 更新图表数据
            cpuUsageData.add(usage);
            cpuTempData.add(tempC != null ? tempC : 0f);
            
            // 保持数据点数量
            if (cpuUsageData.size() > 60) {
                cpuUsageData.remove(0);
                cpuTempData.remove(0);
            }
            
            // 更新图表
            cpuUsageChart.loadHistoricalData(cpuUsageData, cpuTempData, new ArrayList<>(), new ArrayList<>());
        }
    }
    
    // 恢复原始的 updateMemoryData 方法
    private void updateMemoryData() {
        MemoryUtils.MemoryData memoryData = MemoryUtils.getMemoryData();
        if (memoryData != null) {
            float usagePercent = memoryData.getUsagePercent();
            long totalMemory = memoryData.getTotalMemory();
            long usedMemory = memoryData.getUsedMemory();
            long availableMemory = memoryData.getAvailableMemory();
            float frequency = getCurrentCpuFrequency();
            
            // 更新UI
            tvMemoryUsagePercent.setText(String.format("%.1f%%", usagePercent));
            tvTotalMemory.setText(String.format("%d MB", totalMemory));
            tvUsedMemory.setText(String.format("%d MB", usedMemory));
            tvAvailableMemory.setText(String.format("%d MB", availableMemory));
            
            // 更新图表数据
            memoryUsageData.add(usagePercent);
            cpuFreqData.add(frequency);
            
            // 保持数据点数量
            if (memoryUsageData.size() > 60) {
                memoryUsageData.remove(0);
                cpuFreqData.remove(0);
            }
            
            // 更新图表
            memoryUsageChart.loadHistoricalData(new ArrayList<>(), new ArrayList<>(), cpuFreqData, memoryUsageData);
        }
    }
    
    // 获取当前CPU频率
    private float getCurrentCpuFrequency() {
        try {
            CpuData cpuData = CpuUtils.getCpuData();
            return cpuData != null ? cpuData.getFrequency() : 0f;
        } catch (Exception e) {
            return 0f;
        }
    }
    
    // 添加回 startDataUpdate 方法
    private void startDataUpdate() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                handler.post(() -> {
                    updateDisplayData();
                });
            }
        }, 0, 1000);
    }

    // 确保 updateDisplayData 方法存在
    private void updateDisplayData() {
        try {
            // 更新CPU数据
            CpuData cpuData = CpuUtils.getCpuData();
            if (cpuData != null) {
                if (isExpanded) {
                    // 大窗口模式
                    updateCpuData();
                } else {
                    // 小窗口模式
                    tvCpuUsage.setText(String.format(Locale.getDefault(), "CPU: %.0f%%", cpuData.getUsage()));
                    tvCpuFreq.setText(String.format(Locale.getDefault(), "%.0f MHz", cpuData.getFrequency()));
                    if (cpuData.getTemperatureC() != null) {
                        tvCpuTemp.setText(String.format(Locale.getDefault(), "%.1f°C", cpuData.getTemperatureC()));
                    } else {
                        tvCpuTemp.setText("--°C");
                    }
                }
            }
            
            // 更新内存数据
            MemoryUtils.MemoryData memoryData = MemoryUtils.getMemoryData();
            if (memoryData != null) {
                if (isExpanded) {
                    // 大窗口模式
                    updateMemoryData();
                } else {
                    // 小窗口模式
                    tvMemoryUsage.setText(String.format(Locale.getDefault(), "内存: %.0f%%", memoryData.getUsagePercent()));
                    tvMemoryTotal.setText(String.format(Locale.getDefault(), "总计: %d MB", memoryData.getTotalMemory()));
                    tvMemoryUsed.setText(String.format(Locale.getDefault(), "已用: %d MB", memoryData.getUsedMemory()));
                }
            }
            
            // 更新运行时间
            updateUptime();
            
        } catch (Exception e) {
            Log.e(TAG, "Error updating display data", e);
        }
    }

// 运行时间计算方法 - 显示系统启动时间
private void updateUptime() {
    if (tvUptime == null) {
        Log.e(TAG, "tvUptime is null, check if R.id.tv_uptime exists in layout");
        return;
    }
    
    // 获取系统运行时间
    long uptimeMillis = SystemClock.uptimeMillis();
    long days = uptimeMillis / (24 * 60 * 60 * 1000);
    long hours = (uptimeMillis % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000);
    long minutes = (uptimeMillis % (60 * 60 * 1000)) / (60 * 1000);
    long seconds = (uptimeMillis % (60 * 1000)) / 1000;
    
    String uptimeText;
    if (days > 0) {
        uptimeText = String.format("%d天%d小时%d分钟", days, hours, minutes);
    } else if (hours > 0) {
        uptimeText = String.format("%d:%02d:%02d", hours, minutes, seconds);
    } else if (minutes > 0) {
        uptimeText = String.format("00:%02d:%02d", minutes, seconds);
    } else {
        uptimeText = String.format("00:00:%02d", seconds);
    }
    
    tvUptime.setText(uptimeText);
    Log.d(TAG, "System uptime updated: " + uptimeText);
}

    public void startFloatingWindow(Context context) {
        // 检测并移除现有窗口
        removeExistingWindow();

        try {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            LayoutInflater inflater = LayoutInflater.from(context);
            floatingView = inflater.inflate(R.layout.floating_monitor_window_large, null);

            // 设置窗口参数 - 使用FLAG_NOT_FOCUSABLE实现完全事件穿透
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            params.gravity = Gravity.TOP | Gravity.START;
            params.x = 50;
            params.y = 50;

            // 添加窗口
            windowManager.addView(floatingView, params);
            isWindowVisible = true;
            isExpanded = true; // 标记为大窗口
        

            // 初始化大窗口视图和数据更新
            initLargeViews();
            setupCharts();
            initCpuInfo();
            this.handler = new Handler(Looper.getMainLooper());
            startDataUpdate();
            
            Log.d(TAG, "Large floating window started successfully");

        } catch (Exception e) {
            Log.e(TAG, "Error starting large floating window", e);
        }
    }

    // 启动小窗口
    public void startSmallFloatingWindow(Context context) {
        // 检测并移除现有窗口
        removeExistingWindow();

        try {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            LayoutInflater inflater = LayoutInflater.from(context);
            floatingView = inflater.inflate(R.layout.floating_monitor_window_small, null);

            // 设置窗口参数 - 使用FLAG_NOT_FOCUSABLE实现完全事件穿透
            WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                    PixelFormat.TRANSLUCENT
            );

            params.gravity = Gravity.TOP | Gravity.START;
            params.x = 100;
            params.y = 100;

            // 添加窗口
            windowManager.addView(floatingView, params);
            isWindowVisible = true;
            isExpanded = false; // 标记为小窗口
            
         

            // 初始化小窗口视图和数据更新
            initSmallViews();
            this.handler = new Handler(Looper.getMainLooper());
            startDataUpdate();
            
            Log.d(TAG, "Small floating window started successfully");

        } catch (Exception e) {
            Log.e(TAG, "Error starting small floating window", e);
        }
    }

    public static void createAndStart(Context context) {
        FloatingMonitorWindow window = new FloatingMonitorWindow();
        window.startFloatingWindow(context);
    }
    
    // 静态方法：创建并启动小窗口
    public static void createAndStartSmall(Context context) {
        FloatingMonitorWindow window = new FloatingMonitorWindow();
        window.startSmallFloatingWindow(context);
    }

    
    // 关闭悬浮窗
    public void hideFloatingWindow() {
        if (windowManager != null && floatingView != null) {
            try {
                windowManager.removeView(floatingView);
                isWindowVisible = false;
                isExpanded = false;
                stopDataUpdate();
                
                // 清理静态实例引用
                currentInstance = null;
                
                Log.d(TAG, "Floating window closed");
            } catch (Exception e) {
                Log.e(TAG, "Error closing floating window", e);
            }
        }
    }
    
    // 停止数据更新
    private void stopDataUpdate() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}